package com.itheima.commons.utils;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.PutObjectResult;

import java.io.ByteArrayInputStream;

public class UploadPicUtil {
    private static String accessKey_id;
    private static String accessKey_secret;
    private static String endpoint;
    private static String bucketname;
    private static String picurl;

    static {
        accessKey_id = ProLoadUtil.proload().getProperty("oss.accessKey_id");
        accessKey_secret = ProLoadUtil.proload().getProperty("oss.accessKey_secret");
        endpoint = ProLoadUtil.proload().getProperty("oss.endpoint");
        bucketname = ProLoadUtil.proload().getProperty("oss.bucketname");
        picurl = ProLoadUtil.proload().getProperty("oss.picurl");
    }


    public static String uploadPic(byte[] imageData, String fileSuffixName) {


        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKey_id, accessKey_secret);
        // 我们在进行存储文件的时候 不能把所有的文件都存储到同一个目录中
        // 对上传目录进行分离 目录分离算法 根据一个文件名称 --> 自动生成目录层级
        String filePath = getFilePath(fileSuffixName);
        PutObjectResult result = ossClient.putObject(bucketname, filePath, new ByteArrayInputStream(imageData));

        // https://hztanhua.oss-cn-hangzhou.aliyuncs.com/images/2021/12/04/06a5a91e2cd941539605b41aacc7d1c6.jpg
        ossClient.shutdown();
        // 返回上传成功后的图片地址
        return picurl + filePath;
    }

    private static String getFilePath(String fileSuffixName) {
        DateTime date = DateUtil.date();
        int year = date.year();
        int month = date.month();
        int day = date.dayOfMonth();

        String path = "images/" + year + "/" + month + "/" + day + "/" + UUID.fastUUID().toString() + "." + fileSuffixName;
        System.out.println(path);
        return path;
    }

}
